using System;
using System.Collections.Generic;
using System.Linq;
using HengTong.Model._Admin;
using HengTong.Model.Db;
using HengTong.Model.Db.System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using WalkingTec.Mvvm.Core;

namespace HengTong.Model.Extension;

public static class WtmExtension
{
    /// <summary>
    /// 获取站点配置
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static SysSiteConfig GetSiteConfig(this WTMContext context)
    {
        var scope = context.ServiceProvider.CreateScope();
        var memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
        var config = memoryCache.GetOrCreate(nameof(GetSiteConfig), entry =>
        {
            entry.SlidingExpiration = TimeSpan.FromHours(12);
            var config = context.DC.Set<SysSiteConfig>()
                .AsNoTracking()
                .FirstOrDefault();
            return config;
        });
        return config;
    }

    /// <summary>
    /// 清除站点配置缓存
    /// </summary>
    /// <param name="context"></param>
    public static void ClearSiteConfig(this WTMContext context)
    {
        var scope = context.ServiceProvider.CreateScope();
        var memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
        memoryCache.Remove(nameof(GetSiteConfig));
    }
    
    /// <summary>
    /// 清除所有用户缓存
    /// </summary>
    /// <param name="context"></param>
    public static void RemoveAllAccountsCache(this WTMContext context)
    {
        var scope = context.ServiceProvider.CreateScope();
        var memory = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
        var key = $"{nameof(GlobalData)}.AllAccounts";
        memory.Remove(key);
    }
    
    /// <summary>
    /// 获取所有用户缓存
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static List<FrameworkUser> AllAccounts(this WTMContext context)
    {
        var scope = context.ServiceProvider.CreateScope();
        var memory = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
        var key = $"{nameof(GlobalData)}.AllAccounts";
        var data = memory.GetOrCreate(key, entry =>
        {
            entry.SetSlidingExpiration(TimeSpan.FromMinutes(60 * 24));
            return context.DC.Set<FrameworkUser>()
                .AsNoTracking()
                .ToList();
        });
        return data;
    }
    
    /// <summary>
    /// 格式化用户名
    /// </summary>
    /// <param name="context"></param>
    /// <param name="itcode"></param>
    /// <returns></returns>
    public static string FormatUsername(this WTMContext context, string itcode)
    {
        var user = context.AllAccounts().FirstOrDefault(x => x.ITCode == itcode);
        if (user != null)
        {
            return $"{user.Name}({user.ITCode})";
        }
        return itcode;
    }
}